﻿using MaterialManagement.Domain.ERP;
using MediatR;
using Microsoft.Extensions.Logging;
using ProductionLine.API.Application.Command.BOM;
using ProductionLine.API.Application.Command.PlanDetail.Read;
using ProductionLine.Domain.BOM;
using ProductionLine.Domain.Material;
using ProductionLine.Domain.Plan;
using ProductionLine.Domain.Product;
using ProductionLine.Domain.ProductLine;
using ProductionLine.ErrorCode;
using ProductionLine.Extensions;
using ProductionLine.Infrastructure.Interface;
using Serilog;
using Serilog.Core;

namespace ProductionLine.API.Application.Handler.BOM
{
    public class GetBOMHandler : IRequestHandler<GetBOMCommand, APIResult<List<BOMDTO>>>
    {
        IBaseRepository<BOMModel> bomRepo;
        IBaseRepository<MaterialInfoModel> materRepo;
        IBaseRepository<PlanModel> productRepo;

        public GetBOMHandler(IBaseRepository<BOMModel> bomRepo, IBaseRepository<MaterialInfoModel> materRepo, IBaseRepository<PlanModel> productRepo)
        {
            this.bomRepo = bomRepo;
            this.materRepo = materRepo;
            this.productRepo = productRepo;
          
        }

        public async Task<APIResult<List<BOMDTO>>> Handle(GetBOMCommand request, CancellationToken cancellationToken)
        {
            APIPaging<List<BOMDTO>> res = new APIPaging<List<BOMDTO>>();
            var lists = bomRepo.GetAll().Where(c => !c.IsDel);
            var mater = materRepo.GetAll().Where(c => !c.IsDel);
            var product = productRepo.GetAll();
            var linq = from a in lists
                       join b in mater on a.MaterialId equals b.MaterialId
                       join c in product on a.PlanId equals c.PlanId
                       select new BOMDTO
                       {
                           BOMId = a.BOMId,
                           PlanId = c.PlanId,
                           ProductName = c.ProductName,
                           Specification = c.Specification,
                           UnitName = c.UnitName,
                           MaterialId = b.MaterialId,
                           BOMCode = a.BOMCode,
                           BOMVertion = a.BOMVertion,
                           MaterialCode = b.MaterialCode,
                           MaterialName = b.MaterialName
                       };

            res.Msg = "查询BOM组成成功";
            res.Code = APIEnum.Success;
            res.Data = linq.ToList();
            return await Task.FromResult(res);
        }
    }
}
